package logs

import (
	"fmt"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"runtime"
	"strings"
)

type ILog interface {
	ILogWriter

	ILogCtr
	ILogCallerSkip
}

type ILogWriter interface {
	Debug(log string, params ...interface{})
	Info(log string, params ...interface{})
	Warn(log string, params ...interface{})
	Error(log string, params ...interface{})
	Panic(log string, params ...interface{})
	Fatal(log string, params ...interface{})
	Write(p []byte) (n int, err error)
}

type ILogCtr interface {
	Ctl(bool) ILog
}

type ILogCallerSkip interface {
	CallerSkip(offset int) ILog
}

type logHelper struct {
}

func (l logHelper) initConfig(c *configstc.LogConfig) {
	c.LLevel = strings.ToUpper(c.LLevel)
	c.LogLevel = strings.ToUpper(c.LLevel)
}

func (l logHelper) lFilepath(c *configstc.LogConfig, skip int) string {
	if c == nil {
		return ""
	}

	switch c.LFilepath {
	case 1:
		//短文件名
		_, file, line, _ := runtime.Caller(l.lCallerSkip(c) + skip)
		if index := strings.LastIndex(file, "/"); index >= 0 {
			file = file[index+1:]
		} else if index = strings.LastIndex(file, "\\"); index >= 0 {
			file = file[index+1:]
		}
		return fmt.Sprintf("%s:%d", file, line)
	case 2:
		//完整文件名
		_, file, line, _ := runtime.Caller(l.lCallerSkip(c) + skip)
		return fmt.Sprintf("%s:%d", file, line)
	default:
		return ""
	}
}

func (l logHelper) lCallerSkip(c *configstc.LogConfig) int {
	if c == nil {
		return 0
	}

	return c.LCallerSkip
}

func (l logHelper) lLogPath(c *configstc.LogConfig) string {
	if c == nil {
		return ""
	}
	if len(c.LPath) > 0 {
		return c.LPath
	}
	return c.LogPath
}

func (l logHelper) lLogLevel(c *configstc.LogConfig) string {
	if c == nil {
		return "DEBUG"
	}
	if len(c.LLevel) > 0 {
		return strings.ToUpper(c.LLevel)
	}
	return strings.ToUpper(c.LogLevel)
}

func (l logHelper) lLogLevelInt(c *configstc.LogConfig) LogLevel {
	return NameToLogLevel(l.lLogLevel(c))
}
